package com.sbeam.service;

import com.sbeam.vo.ImageVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

@Service
public class ImageServiceImpl implements ImageService{

    private String rootPath = "D:/sbeam/images";
    private String urlPath = "http://manage.sbeam.com";

    @Override
    public ImageVo upload(MultipartFile image) {
        //防止大小写冲突，转小写
        String imageOldName = image.getOriginalFilename().toLowerCase();
        //1.利用正则表达式判断是否为指定类型图片
        if (!imageOldName.matches("^.+\\.(jpg|png)$")) {
            return null;
        }
        System.out.println("图片类型正确");
        //2.校验是否具备图片属性
        try {
            BufferedImage bufferedImage = ImageIO.read(image.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width == 0 || height == 0){
                return null;
            }
            System.out.println("图片具备相应属性");
            //3.目录层级划分
            String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String localPath = rootPath+datePath;// F:/sbeam/images/2021/10/30
            File xxx = new File(localPath);
            if (!xxx.exists()){
                xxx.mkdirs();
            }
            //4.使用uuid实现文件自定义名，防止重名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            int index = imageOldName.lastIndexOf(".");
            String fileType = imageOldName.substring(index);
            String imageNewName = uuid+fileType;
            //5.实现文件上传
            String path = localPath+imageNewName;
            image.transferTo(new File(path));
            System.out.println("至此，图片已经完成上传");
            //6.实现数据回显
            String virtualPath = datePath+imageNewName;
            String imageName = imageNewName;
            String url = urlPath+virtualPath;
            return new ImageVo(virtualPath,url,imageName);
        }catch (IOException io){
            io.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean deleteImage(String virtualPath) {
        String path = rootPath+virtualPath;
        File file = new File(path);
        if (file.exists()){
            return file.delete();
        }
        return false;
    }
}
